package com.example.tbag.healthcare.Activity;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
import android.widget.TextView;

import com.example.tbag.healthcare.Model.Cache;
import com.example.tbag.healthcare.Model.DragInfo;
import com.example.tbag.healthcare.R;
import com.example.tbag.healthcare.Util.CallPhoneUtil;
import com.example.tbag.healthcare.Util.DatabaseHelper;
import com.example.tbag.healthcare.Util.ToastUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.BindViews;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by tbag on 2017/4/23.
 */

public class AddDragActivity extends AppCompatActivity {
    private boolean isShow = false;
    private boolean change = false;
    private List<Cache> caches = new ArrayList<>();
    private int id;
    private int _id;
    private DragInfo dragInfo;
    private DatabaseHelper helper;
    @BindViews({ R.id.edit1,R.id.edit2, R.id.edit3, R.id.edit4, R.id.edit5,R.id.edit6})
    List<EditText> editTexts;

    @BindView(R.id.text)
    TextView textView;

    @OnClick(R.id.btn_back)
    public void back() {
        this.finish();
    }
    @OnClick(R.id.right_btn)
    public void callForHelp() {
        CallPhoneUtil.call(this);
    }

    @OnClick(R.id.btn1)
    public void exit() {
        this.finish();
    }

    @OnClick(R.id.btn2)
    public void checkAndSave() {
        int index = 0;
        ContentValues cv = new ContentValues();
        for (EditText editText : editTexts) {
            String text = editText.getText().toString().trim();
            switch (index) {
                case 0:
                    if (text.isEmpty()) {
                        ToastUtil.show(this, "日期不能为空");
                        return;
                    }
                    cv.put("time", text);
                    break;
                case 1:
                    if (text.isEmpty()) {
                        ToastUtil.show(this, "医嘱不能为空");
                        return;
                    }
                    cv.put("cure", text);
                    break;
                case 2:
                    if (text.isEmpty()) {
                        ToastUtil.show(this, "处方不能为空");
                        return;
                    }
                    cv.put("drag", text);
                    break;
                case 3:
                    if (text.isEmpty()) {
                        ToastUtil.show(this, "价格不能为空");
                        return;
                    }
                    cv.put("price", text);
                    break;
                case 4:
                    if (text.isEmpty()) {
                        ToastUtil.show(this, "次数不能为空");
                        return;
                    }
                    if(!text.equals(dragInfo.count)){
                        change = true;
                    }
                    cv.put("count", text);
                    break;
                case 5:
                    if (text.isEmpty()) {
                        ToastUtil.show(this, "完成度不能为空");
                        return;
                    }
                    cv.put("done", text);
                    break;
            }
            index++;
        }
        if(isShow){
            helper.getWritableDatabase().update("drag",cv,"_id = ?",new String[]{id+""});
            if(change){
                int a = Integer.parseInt(dragInfo.count);
                int b = Integer.parseInt(cv.getAsString("count"));
                int changeNum = Integer.parseInt(dragInfo.price)*(b-a);
                queryPeople(_id,changeNum);
            }
            ToastUtil.show(this, "修改成功");
        }else {
            cv.put("id", id + "");
            helper.getWritableDatabase().insert("drag", null, cv);
            int a = Integer.parseInt(cv.getAsString("price"));
            int b = Integer.parseInt(cv.getAsString("count"));
            int changeNum =a*b;
            queryPeople(_id,changeNum);
            ToastUtil.show(this, "保存成功");
        }
        new Handler(getMainLooper()).postDelayed(new Runnable() {
            @Override
            public void run() {
                exit();
            }
        }, 800);
    }

    private void queryPeople(int id,int num) {
        Cursor cursor = helper.getWritableDatabase().query("people", null, "id=?", new String[]{id + ""}, null, null, null);
        if (cursor == null) {
            ToastUtil.show(this, "出问题啦");
            this.finish();
            return;
        }
        cursor.moveToFirst();
        String usedMoney = cursor.getString(cursor.getColumnIndex("usedMoney"));
        String leftMoney = cursor.getString(cursor.getColumnIndex("leftMoney"));
        int uesd = Integer.parseInt(usedMoney)+num;
        int left = Integer.parseInt(leftMoney)-num;
        ContentValues cv = new ContentValues();
        cv.put("usedMoney",uesd+"");
        cv.put("leftMoney",left+"");
        helper.getWritableDatabase().update("people",cv,"id = ?", new String[]{id + ""});
    }


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_drag_info);
        ButterKnife.bind(this);
        id = getIntent().getIntExtra("id",0);
        if(getIntent().getIntExtra("type",1)==0){
            isShow = true;
            textView.setText("修改药品信息");
            change();
        }
        helper = new DatabaseHelper(this);
        editTexts.get(2).addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                for(Cache cache:caches){
                    if(cache.title.equals(s.toString())){
                        editTexts.get(3).setText(cache.money);
                        return;
                    }
                }
                ToastUtil.show(AddDragActivity.this, "请检查药品名称是否存在");
            }
        });
        getPersons();
    }

    public void getPersons() {
        SQLiteDatabase db = helper.getReadableDatabase();
        Cursor cursor = db.query("med",null,null,null,null,null,null);
        if (cursor != null && cursor.moveToFirst()) {
            caches.add(getHumanInfo(cursor));
            while (cursor.moveToNext()) {
                caches.add(getHumanInfo(cursor));
            }
            cursor.close();
            db.close();
        }
    }

    public Cache getHumanInfo(Cursor cursor) {
        String date = cursor.getString(cursor.getColumnIndex("name"));
        String time = cursor.getString(cursor.getColumnIndex("money"));
        int id = cursor.getInt(cursor.getColumnIndex("_id"));
        Cache humanInfo = new Cache(date, time,id);
        return humanInfo;
    }

    public DragInfo getPerson() {
        SQLiteDatabase db = helper.getReadableDatabase();
        Cursor cursor = db.query("drag",null,"_id =?",new String[]{id+""},null,null,null);
        if (cursor != null && cursor.moveToFirst()) {
            DragInfo humanInfo = getDragInfor(cursor);
            cursor.close();
            db.close();
            return humanInfo;
        }
        ToastUtil.show(this,"系统出现问题");
        finish();
        return null;
    }

    public DragInfo getDragInfor(Cursor cursor) {
        String time = cursor.getString(cursor.getColumnIndex("time"));
        String drag = cursor.getString(cursor.getColumnIndex("drag"));
        String count = cursor.getString(cursor.getColumnIndex("count"));
        String people = cursor.getString(cursor.getColumnIndex("done"));
        int id = cursor.getInt(cursor.getColumnIndex("_id"));
        String price = cursor.getString(cursor.getColumnIndex("price"));
        String cure = cursor.getString(cursor.getColumnIndex("cure"));
        _id =  cursor.getInt(cursor.getColumnIndex("id"));
        dragInfo = new DragInfo(id,time, cure,drag,price, count, people);
        return dragInfo;
    }

    private void change() {
        DragInfo humanInfo = getPerson();
        editTexts.get(0).setText(humanInfo.time);
        editTexts.get(1).setText(humanInfo.cure);
        editTexts.get(2).setText(humanInfo.drag);
        editTexts.get(3).setText(humanInfo.count);
        editTexts.get(4).setText(humanInfo.price);
        editTexts.get(5).setText(humanInfo.done);
    }
    
    
}
